package com.qujia.common.utils;

import com.qujia.common.enums.IBaseEnum;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @date 2023/12/29
 */
public class EnumsContainer {

    private final static Map<Class, Map<Object, IBaseEnum>> ENUM_MAP = new ConcurrentHashMap<>();

    public static <K,E extends IBaseEnum<K>> E getEnumByKey(Class<E> clazz, K key){
        if (clazz.isEnum()) {
            Map<Object, IBaseEnum> enumKeyMap = ENUM_MAP.get(clazz);
            if (enumKeyMap == null) {
                HashMap<Object, IBaseEnum> map = new HashMap<>();
                E[] enumConstants = clazz.getEnumConstants();
                for (E enumConstant : enumConstants) {
                    map.put(enumConstant.getKey(),enumConstant);
                }
                enumKeyMap = map;
                ENUM_MAP.put(clazz, enumKeyMap);
            }
            return (E) enumKeyMap.get(key);
        }
        return null;
    }

    public static <K,E extends IBaseEnum<K>> E getEnumByKey(Class<E> clazz, K key, E def){
        E enumByKey = getEnumByKey(clazz, key);
        return enumByKey == null ? def : enumByKey;
    }

}
